<template>
  <vab-dialog v-model="dialogFormVisible" append-to-body :title="title" width="500px" @close="close">
    <el-form ref="formRef" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="名称" prop="name">
        <el-input v-model.trim="form.name" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </vab-dialog>
</template>

<script lang="ts" setup>
import { doDepartmentEdit as doEdit } from '/@/api/sys'

defineOptions({
  name: 'Edit',
})

const emit = defineEmits(['fetch-data'])
const $baseMessage = inject<any>('$baseMessage')
const formRef = ref<any>(null)
const title = ref<string>('')
const dialogFormVisible = ref<boolean>(false)
const form = reactive<any>({
  departmentId: '',
  name: '',
  departType: 0,
  firstId: 0,
  secondId: 0,
})

const rules = reactive<any>({
  departmentIdentity: [{ required: true, trigger: 'change', message: '部门身份必须选择' }],
  roleIds: [{ required: true, trigger: 'change', message: '角色必须选择' }],
  departmentIds: [{ required: true, trigger: 'change', message: '部门必须选择' }],
})

const showEdit = (row: any) => {
  dialogFormVisible.value = true
  nextTick(() => {
    if (!row) title.value = '添加'
    else {
      title.value = '编辑'
      Object.assign(form, row)
    }
  })
}

defineExpose({
  showEdit,
})

const close = () => {
  formRef.value.clearValidate()
  formRef.value.resetFields()
  emit('fetch-data')
  dialogFormVisible.value = false
}

const save = () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      const { message }: any = await doEdit(form)
      $baseMessage(message, 'success', 'hey')
      close()
    }
  })
}

onBeforeMount(() => {})
</script>
